<template>
  <div>
    <el-card>
      <template #header><h2>床位管理</h2></template>

      <!-- 搜索区域 -->
      <el-form :model="searchForm" inline>
        <el-form-item label="客户姓名">
          <el-input v-model="searchForm.customerName" placeholder="客户姓名" clearable />
        </el-form-item>
       <el-form-item label="最早起始日期">
         <el-date-picker
           v-model="searchForm.startDate"
           type="date"
           placeholder="最早起始日期"
           format="YYYY-MM-DD"
           value-format="YYYY-MM-DD"
         />
       </el-form-item>
       <el-form-item label="最晚起始日期">
         <el-date-picker
           v-model="searchForm.endDate"
           type="date"
           placeholder="最晚起始日期"
           format="YYYY-MM-DD"
           value-format="YYYY-MM-DD"
         />
       </el-form-item>
        <el-form-item label="使用状态">
          <el-select v-model="searchForm.isDeleted" placeholder="使用状态" style="width: 140px">
            <el-option label="正在使用" :value="false" />
            <el-option label="使用历史" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadBedData">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格 -->
      <el-table :data="tableData" border stripe style="width: 100%; margin-top: 12px">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="customerName" label="客户姓名" width="120" />
        <el-table-column label="性别" width="80">
          <template #default="{ row }">{{ row.customerSex === 0 ? '男' : '女' }}</template>
        </el-table-column>
        <el-table-column prop="bedNumber" label="床位号" width="120" />
        <el-table-column prop="assignStartTime" label="起始日期" width="140" :formatter="formatDate" />
        <el-table-column prop="assignEndTime" label="结束日期" width="140" :formatter="formatDate" />
		<el-table-column label="操作">
		  <template #default="{ row }">
		    <template v-if="!row.isDeleted">
		      <el-button type="success" size="small" @click="openSwapDialog(row)">床位调换</el-button>
		      <el-button type="primary" size="small" @click="editData(row)">修改</el-button>
		    </template>
		    <template v-else>
		      <el-tag type="info">历史记录</el-tag>
		    </template>
		  </template>
		</el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="loadBedData"
        @size-change="loadBedData"
        style="margin-top: 16px; text-align: right;"
      />
    </el-card>

    <!-- 编辑抽屉 -->
    <el-drawer v-model="drawerVisible" :title="drawerTitle" size="40%">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="客户姓名">
          <el-input v-model="formData.customerName" disabled />
        </el-form-item>
        <el-form-item label="起始日期">
          <el-date-picker v-model="formData.assignStartTime" type="date" disabled />
        </el-form-item>
        <el-form-item label="结束日期">
          <el-date-picker v-model="formData.assignEndTime" type="date" placeholder="结束日期" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitData">{{ drawerTitle }}</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
	
	<!-- 床位调换对话框 -->
	    <el-dialog v-model="swapDialogVisible" title="床位调换" width="600px">
	      <el-form :model="swapForm" label-width="100px">
	        <el-form-item label="当前客户">
	          <el-input v-model="currentCustomer.name" disabled />
	        </el-form-item>
	        <el-form-item label="当前床位">
	          <el-input v-model="currentCustomer.bedInfo" disabled />
	        </el-form-item>
	        
			<el-form-item label="楼栋" prop="building">
			  <el-input v-model="swapForm.building" disabled />
			</el-form-item>
	        
	        <el-form-item label="房间号">
	          <el-select 
	            v-model="swapForm.roomNumber" 
	            placeholder="请选择房间号"
	            @change="loadVacantBeds"
	            :loading="roomLoading"
	          >
	            <el-option 
	              v-for="room in roomList" 
	              :key="room" 
	              :label="room" 
	              :value="room" 
	            />
	          </el-select>
	        </el-form-item>
	        
	        <el-form-item label="床位号">
	          <el-select 
	            v-model="swapForm.bedNumber" 
	            placeholder="请选择床位号"
	            :loading="bedLoading"
	          >
	            <el-option 
	              v-for="bed in bedList" 
	              :key="bed" 
	              :label="bed" 
	              :value="bed" 
	            />
	          </el-select>
	        </el-form-item>
	      </el-form>
	      
	      <template #footer>
	        <el-button @click="swapDialogVisible = false">取消</el-button>
	        <el-button type="primary" @click="confirmSwap" :loading="swapping">确定调换</el-button>
	      </template>
	    </el-dialog>
	
  </div>
</template>

<script setup>
import { ref, reactive, inject } from 'vue'
import dayjs from 'dayjs'
import { ElMessage } from 'element-plus'
import qs from 'qs'

// 注入 axios
const axios = inject('axios')

// 搜索 & 分页
const searchForm = reactive({
  customerName: '',
  startDate: '',
  endDate: '',
  isDeleted: false,
})
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const loading = ref(false)

// 抽屉 & 表单
const drawerVisible = ref(false)
const drawerTitle = ref('修改床位详情')
const formData = reactive({
  id: null,
  customerName: '',
  assignStartTime: '',
  assignEndTime: '',
})

// 床位调换相关
const swapDialogVisible = ref(false)
const swapForm = reactive({
  building: '606',
  roomNumber: '',
  bedNumber: ''
})
const currentCustomer = reactive({
  id: null,
  name: '',
  bedInfo: ''
})
const roomList = ref([])
const bedList = ref([])
const roomLoading = ref(false)
const bedLoading = ref(false)
const swapping = ref(false)

// 格式化日期
const formatDate = (_, __, val) => (val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '')

// 加载床位分配
async function loadBedData() {
  const resp = await axios.post(
    'BedAssignmentController/queryBedAssignmentByCondition',
    qs.stringify({
      cur: currentPage.value,
      number: pageSize.value,
      name: searchForm.customerName,
      assignStartTimeBegin: searchForm.startDate,
      assignStartTimeEnd: searchForm.endDate,
      isDeleted: searchForm.isDeleted,
    })
  )
  const rb = resp.data
  if (rb.status !== 200) {
	  tableData.value = rb.data
	  total.value = rb.total
    return ElMessage.error('加载失败：' + rb.msg)
  }
  tableData.value = rb.data
  total.value = rb.total
}

// 编辑
function editData(row) {
  formData.id = row.id
  formData.customerName = row.customerName
  formData.assignStartTime = dayjs(row.assignStartTime)
  formData.assignEndTime = row.assignEndTime ? dayjs(row.assignEndTime) : null
  drawerVisible.value = true
}

// 提交
async function submitData() {
  if (!formData.assignEndTime) {
    return ElMessage.warning('请填写结束日期')
  }

  const payload = {
    id: formData.id,
    assignEndTime: dayjs(formData.assignEndTime).format('YYYY-MM-DD'),
  }

  const resp = await axios.post(
    '/BedAssignmentController/updateBedAssignment',
    qs.stringify(payload)
  )
  if (resp.data.status === 200) {
    ElMessage.success('修改成功')
    drawerVisible.value = false
    loadBedData()
  } else {
    ElMessage.error('修改失败：' + resp.data.message)
  }
}

// 打开床位调换对话框
async function openSwapDialog(row) {
  currentCustomer.id = row.customerId
  currentCustomer.name = row.customerName
  currentCustomer.bedInfo = row.bedNumber
  
  // 重置表单
  swapForm.building = '606'
  swapForm.roomNumber = ''
  swapForm.bedNumber = ''
  roomList.value = []
  bedList.value = []
  
  swapDialogVisible.value = true
  
  // 加载房间列表
  loadRooms()
}

// 加载房间列表
async function loadRooms() {
  if (!swapForm.building) return
  
  roomLoading.value = true
  try {
    const resp = await axios.get('RoomInfoController/queryAllRoomNumber')
    
    if (resp.data.status === 200) {
      roomList.value = resp.data.data
    } else {
      ElMessage.error('加载房间列表失败: ' + resp.data.message)
    }
  } catch (error) {
    ElMessage.error('加载房间列表出错: ' + error.message)
  } finally {
    roomLoading.value = false
  }
}

// 加载空闲床位
async function loadVacantBeds(room) {
  
  bedLoading.value = true
  try {
    const resp = await axios.post('BedInfoController/queryVacantBedNumberByRoomNumber', qs.stringify({ roomNumber: swapForm.roomNumber}))
    
    if (resp.data.status === 200) {
      bedList.value = resp.data.data
    } else {
      ElMessage.error('加载床位列表失败: ' + resp.data.message)
    }
  } catch (error) {
    ElMessage.error('加载床位列表出错: ' + error.message)
  } finally {
    bedLoading.value = false
  }
}

// 确认调换床位
async function confirmSwap() {
  if (!swapForm.bedNumber) {
    ElMessage.warning('请选择要调换的床位')
    return
  }
  
  swapping.value = true
  try {
    const resp = await axios.post('BedAssignmentController/swapBed', qs.stringify({
      customerId: currentCustomer.id,
      newBedNumber: swapForm.bedNumber
    }))
    
    if (resp.data.status === 200) {
      ElMessage.success('床位调换成功')
      swapDialogVisible.value = false
      loadBedData()
    } else {
      ElMessage.error('床位调换失败: ' + resp.data.message)
    }
  } catch (error) {
    ElMessage.error('床位调换出错: ' + error.message)
  } finally {
    swapping.value = false
  }
}

// 初始化加载
loadBedData()
</script>

<style scoped>
.el-form-item {
  margin-right: 12px;
}
.el-table th, .el-table td {
  text-align: center;
}
.el-pagination {
  margin: 16px 0;
  text-align: right;
}
</style>
